import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import { loginMerchant, getCurrentMerchant } from '@/api/merchant'
import type { Merchant, MerchantLoginParams } from '@/api/merchant'

export const useMerchantStore = defineStore('merchant', () => {
  // 状态
  const token = ref<string | null>(localStorage.getItem('merchant_token'))
  const currentMerchant = ref<Merchant | null>(null)
  const loading = ref(false)

  // 计算属性
  const isLoggedIn = computed(() => !!token.value)
  const merchantInfo = computed(() => currentMerchant.value)

  // 方法
  // 登录
  const login = async (loginParams: MerchantLoginParams) => {
    loading.value = true
    try {
      const result = await loginMerchant(loginParams)
      
      if (result.code === 200 && result.data) {
        // 保存token
        const merchantToken = result.data
        token.value = merchantToken
        localStorage.setItem('merchant_token', merchantToken)
        
        console.log('商家登录成功，token:', merchantToken)
        
        // 获取商家信息
        await fetchCurrentMerchant()
        
        console.log('商家登录成功，商家信息:', currentMerchant.value)
        
        return { token: merchantToken, merchant: currentMerchant.value }
      } else {
        throw new Error(result.message || '登录失败')
      }
    } catch (error) {
      console.error('商家登录失败:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  // 获取当前商家信息
  const fetchCurrentMerchant = async () => {
    const currentToken = token.value || localStorage.getItem('merchant_token')
    if (!currentToken) {
      console.log('没有商家token，无法获取商家信息')
      return null
    }
    
    loading.value = true
    try {
      console.log('正在获取商家信息，使用token:', currentToken)
      const response = await getCurrentMerchant()
      
      if (response.code === 200 && response.data) {
        currentMerchant.value = response.data
        console.log('获取商家信息成功:', response.data)
        return response.data
      } else {
        console.error('获取商家信息失败，响应码:', response.code, '消息:', response.message)
        throw new Error(response.message || '获取商家信息失败')
      }
    } catch (error: any) {
      console.error('获取商家信息失败:', error.message || error)
      // 如果是401错误，清除token
      if (error.response && error.response.status === 401) {
        console.log('token无效，清除商家登录状态')
        logout()
      }
      return null
    } finally {
      loading.value = false
    }
  }

  // 登出
  const logout = () => {
    token.value = null
    currentMerchant.value = null
    localStorage.removeItem('merchant_token')
  }

  // 初始化 - 如果有token则获取商家信息
  const initialize = async () => {
    console.log('初始化商家状态, token:', token.value)
    if (token.value) {
      await fetchCurrentMerchant()
    }
  }

  return { 
    token, 
    currentMerchant, 
    loading, 
    isLoggedIn, 
    merchantInfo, 
    login, 
    logout, 
    fetchCurrentMerchant, 
    initialize 
  }
}) 